<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>温度监控系统</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        /* 标签页样式 */
        .tab-container {
            margin: 20px 0;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        .tab {
            padding: 12px 20px;
            cursor: pointer;
            background-color: #f1f1f1;
            border: 1px solid #ddd;
            border-bottom: none;
            border-radius: 4px 4px 0 0;
            margin-right: 5px;
            transition: background-color 0.3s;
        }
        .tab:hover {
            background-color: #e9e9e9;
        }
        .tab.active {
            background-color: #007bff;
            color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        /* 图表容器样式 */
        .chart-container {
            position: relative;
            height: 70vh;
            width: 100%;
            margin-top: 20px;
        }
        .controls {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
        }
        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .loading {
            text-align: center;
            padding: 20px;
            font-size: 18px;
            color: #666;
        }
        .error {
            text-align: center;
            padding: 20px;
            font-size: 18px;
            color: #d9534f;
        }
        .tab-description {
            margin: 15px 0;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #007bff;
        }
        
        /* 设置表单样式 */
        .settings-form {
            max-width: 600px;
            margin: 0 auto;
        }
        
        .settings-form h3 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        
        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            box-sizing: border-box;
        }
        
        .form-control:focus {
            border-color: #007bff;
            outline: none;
            box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
        }
        
        .btn-save {
            width: 100%;
            padding: 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .btn-save:hover {
            background-color: #218838;
        }
        
        .save-message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            text-align: center;
            display: none;
        }
        
        .save-message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .save-message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        /* Token显示样式 */
        .token-display {
            font-weight: bold;
            font-size: 16px;
            word-break: break-all;
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-top: 15px;
            border: 1px solid #dee2e6;
        }
        
        /* 设置链接样式 */
        .settings-link {
            text-align: center;
            padding: 40px 20px;
        }
        
        .settings-link p {
            font-size: 18px;
            color: #555;
            margin-bottom: 20px;
        }
        
        .btn-settings {
            display: inline-block;
            padding: 15px 30px;
            background-color: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 18px;
            transition: background-color 0.3s;
            border: none;
            cursor: pointer;
        }
        
        .btn-settings:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>温度监控系统</h1>
        
        <div class="tab-container">
            <div class="tabs">
                <div class="tab active" onclick="openTab(event, 'tab1')">实时图表</div>
                <div class="tab" onclick="openTab(event, 'tab2')">历史数据</div>
                <div class="tab" onclick="openTab(event, 'tab3')">数据分析</div>
                <div class="tab" onclick="openTab(event, 'tab4')">系统设置</div>
                <div class="tab" onclick="openTab(event, 'tab5')">设备注册</div>
            </div>

            <div id="tab1" class="tab-content active">
                <div class="tab-description">
                    <p>实时温度监控图表，显示最新的温度变化趋势。</p>
                </div>
                
                <div class="controls">
                    <button onclick="loadTemperatureData()">刷新数据</button>
                </div>
                
                <div class="chart-container">
                    <canvas id="temperatureChart"></canvas>
                </div>
                
                <div id="loadingMessage" class="loading" style="display: none;">
                    正在加载数据...
                </div>
                
                <div id="errorMessage" class="error" style="display: none;">
                </div>
            </div>

            <div id="tab2" class="tab-content">
                <div class="tab-description">
                    <p>历史温度数据记录，可查看过去的温度变化情况。</p>
                </div>
                <p>此功能正在开发中...</p>
            </div>

            <div id="tab3" class="tab-content">
                <div class="tab-description">
                    <p>温度数据分析功能，提供统计信息和趋势预测。</p>
                </div>
                <p>此功能正在开发中...</p>
            </div>

            <div id="tab4" class="tab-content">
                <div class="tab-description">
                    <p>系统配置和参数设置。</p>
                </div>
                <div class="settings-form">
                    <h3>系统参数设置</h3>
                    <form id="settingsForm">
                        <div class="form-group">
                            <label for="param1">参数1 - 数据采集间隔(秒):</label>
                            <input type="text" id="param1" name="param1" class="form-control" placeholder="默认值: 30">
                        </div>
                        
                        <div class="form-group">
                            <label for="param2">参数2 - 温度单位:</label>
                            <input type="text" id="param2" name="param2" class="form-control" placeholder="默认值: Celsius">
                        </div>
                        
                        <div class="form-group">
                            <label for="param3">参数3 - 最大报警温度:</label>
                            <input type="text" id="param3" name="param3" class="form-control" placeholder="默认值: 80">
                        </div>
                        
                        <div class="form-group">
                            <label for="param4">参数4 - 最小报警温度:</label>
                            <input type="text" id="param4" name="param4" class="form-control" placeholder="默认值: -10">
                        </div>
                        
                        <div class="form-group">
                            <label for="param5">参数5 - 数据保留天数:</label>
                            <input type="text" id="param5" name="param5" class="form-control" placeholder="默认值: 30">
                        </div>
                        
                        <div class="form-group">
                            <label for="param6">参数6 - 图表刷新间隔(秒):</label>
                            <input type="text" id="param6" name="param6" class="form-control" placeholder="默认值: 60">
                        </div>
                        
                        <div class="form-group">
                            <label for="param7">参数7 - 报警邮箱:</label>
                            <input type="text" id="param7" name="param7" class="form-control" placeholder="默认值: admin@example.com">
                        </div>
                        
                        <div class="form-group">
                            <label for="param8">参数8 - 日志级别:</label>
                            <input type="text" id="param8" name="param8" class="form-control" placeholder="默认值: INFO">
                        </div>
                        
                        <div class="form-group">
                            <label for="param9">参数9 - 传感器名称:</label>
                            <input type="text" id="param9" name="param9" class="form-control" placeholder="默认值: TemperatureSensor1">
                        </div>
                        
                        <div class="form-group">
                            <label for="param10">参数10 - 位置标识:</label>
                            <input type="text" id="param10" name="param10" class="form-control" placeholder="默认值: Room1">
                        </div>
                        
                        <div class="form-group">
                            <button type="button" onclick="saveSettings()" class="btn-save">保存设置</button>
                        </div>
                    </form>
                    <div id="saveMessage" class="save-message"></div>
                </div>
            </div>

            <div id="tab5" class="tab-content">
                <div class="tab-description">
                    <p>注册新设备并生成访问令牌。</p>
                </div>
                <div class="settings-form">
                    <h3>设备注册</h3>
                    <form id="deviceRegisterForm">
                        <div class="form-group">
                            <label for="reg_devid">设备ID (devid):</label>
                            <input type="text" id="reg_devid" name="reg_devid" class="form-control" placeholder="请输入设备ID">
                        </div>
                        
                        <div class="form-group">
                            <label for="reg_devmac">设备MAC地址 (devmac):</label>
                            <input type="text" id="reg_devmac" name="reg_devmac" class="form-control" placeholder="请输入设备MAC地址">
                        </div>
                        
                        <div class="form-group">
                            <button type="button" onclick="generateToken()" class="btn-save">获取Token</button>
                        </div>
                    </form>
                    <div id="registerMessage" class="save-message"></div>
                    <div id="tokenResult" class="token-display" style="display: none;"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let temperatureChart = null;

        // 标签页切换功能
        function openTab(evt, tabName) {
            // 隐藏所有标签内容
            var tabContents = document.getElementsByClassName("tab-content");
            for (var i = 0; i < tabContents.length; i++) {
                tabContents[i].classList.remove("active");
            }

            // 取消所有标签的激活状态
            var tabs = document.getElementsByClassName("tab");
            for (var i = 0; i < tabs.length; i++) {
                tabs[i].classList.remove("active");
            }

            // 显示当前标签内容并设置为激活状态
            document.getElementById(tabName).classList.add("active");
            evt.currentTarget.classList.add("active");
        }

        // 页面加载完成后自动获取数据
        window.onload = function() {
            loadTemperatureData();
        };

        // 加载温度数据
        function loadTemperatureData() {
            // 显示加载提示
            document.getElementById('loadingMessage').style.display = 'block';
            document.getElementById('errorMessage').style.display = 'none';
            
            // 如果已有图表实例，先销毁
            if (temperatureChart) {
                temperatureChart.destroy();
            }
            
            // 发送请求获取数据
            fetch('get_temperature_data.php')
                .then(response => response.json())
                .then(data => {
                    // 隐藏加载提示
                    document.getElementById('loadingMessage').style.display = 'none';
                    
                    if (data.status === 'success') {
                        renderChart(data.data);
                    } else {
                        showError('获取数据失败: ' + data.message);
                    }
                })
                .catch(error => {
                    // 隐藏加载提示
                    document.getElementById('loadingMessage').style.display = 'none';
                    showError('网络错误: ' + error.message);
                });
        }

        // 渲染图表
        function renderChart(chartData) {
            const ctx = document.getElementById('temperatureChart').getContext('2d');
            
            // 提取时间和温度数据
            const timestamps = chartData.map(item => item.datetime);
            const temperatures = chartData.map(item => item.temperature);
            
            // 创建图表
            temperatureChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: timestamps,
                    datasets: [{
                        label: '温度 (°C)',
                        data: temperatures,
                        borderColor: 'rgb(255, 99, 132)',
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        borderWidth: 2,
                        fill: false,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            display: true,
                            title: {
                                display: true,
                                text: '温度 (°C)'
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: '温度变化趋势'
                        },
                        legend: {
                            display: true,
                            position: 'top'
                        }
                    }
                }
            });
        }

        // 显示错误信息
        function showError(message) {
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorMessage').style.display = 'block';
        }
        
        // 保存设置函数
        function saveSettings() {
            // 收集表单数据
            const settings = {};
            for (let i = 1; i <= 10; i++) {
                const element = document.getElementById(`param${i}`);
                settings[`param${i}`] = element.value;
            }
            
            // 显示保存中消息
            const saveMessage = document.getElementById('saveMessage');
            saveMessage.textContent = '正在保存设置...';
            saveMessage.className = 'save-message';
            saveMessage.style.display = 'block';
            
            // 发送数据到服务器保存
            fetch('save_settings.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(settings)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    saveMessage.textContent = '设置保存成功！';
                    saveMessage.className = 'save-message success';
                } else {
                    saveMessage.textContent = '保存失败: ' + data.message;
                    saveMessage.className = 'save-message error';
                }
            })
            .catch(error => {
                saveMessage.textContent = '保存失败: ' + error.message;
                saveMessage.className = 'save-message error';
            });
        }
        
        // 生成Token函数
        function generateToken() {
            // 收集表单数据
            const devid = document.getElementById('reg_devid').value.trim();
            const devmac = document.getElementById('reg_devmac').value.trim();
            
            // 验证输入
            if (!devid || !devmac) {
                showMessage('请填写设备ID和设备MAC地址', 'registerMessage', 'error');
                return;
            }
            
            // 显示加载中消息
            showMessage('正在生成Token...', 'registerMessage', 'save-message');
            
            // 发送数据到服务器生成Token
            fetch('generate_token.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ devid: devid, devmac: devmac })
            })
            .then(response => response.json())
            .then(data => {
                const registerMessage = document.getElementById('registerMessage');
                const tokenResult = document.getElementById('tokenResult');
                
                if (data.status === 'success') {
                    showMessage('Token生成成功！', 'registerMessage', 'save-message success');
                    tokenResult.textContent = 'Token: ' + data.data.token;
                    tokenResult.style.display = 'block';
                } else {
                    showMessage('Token生成失败: ' + data.message, 'registerMessage', 'save-message error');
                    tokenResult.style.display = 'none';
                }
            })
            .catch(error => {
                showMessage('请求失败: ' + error.message, 'registerMessage', 'save-message error');
                document.getElementById('tokenResult').style.display = 'none';
            });
        }
        
        // 显示消息函数
        function showMessage(message, elementId, className) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = className;
            element.style.display = 'block';
        }
        
        // 页面加载时加载现有设置
        window.addEventListener('load', function() {
            fetch('get_settings.php')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 填充表单
                        for (let i = 1; i <= 10; i++) {
                            const element = document.getElementById(`param${i}`);
                            if (element && data.settings[`param${i}`] !== undefined) {
                                element.value = data.settings[`param${i}`];
                            }
                        }
                    }
                })
                .catch(error => {
                    console.log('加载设置失败:', error);
                });
        });
    </script>
</body>
</html>